package com.grain.security.rbac.init;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;

@Component
public class SystemDataInitializer implements ApplicationListener<ContextRefreshedEvent> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired(required = false)
    private List<DataInitializer> dataInitializers;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (CollectionUtils.isNotEmpty(dataInitializers)) {
            dataInitializers.sort((o1, o2) -> o2.getIndex().compareTo(o1.getIndex()));
            dataInitializers.stream().forEach(dataInitializer -> {
                try {
                    dataInitializer.init();
                } catch (Exception e) {
                    logger.info("系统数据初始化失败（"+dataInitializer.getClass().getSimpleName()+"）",e);
                }
            });
        }
    }
}
